class PagesController < ApplicationController
  before_filter :require_login,           :only => [:create,  :edit,    :new,     :update,  :destroy]
  before_filter :require_admin,           :only => [:index,   :new,     :create,  :edit,    :update,  :destroy]
  before_filter :find_page,               :only => [:show,    :edit,    :update,  :destroy]
  before_filter :find_list_items,         :only => [:new,     :edit,    :update]
  before_filter :check_page_permissions,  :only => [:show]
  
  
  def index
    @pages = Page.find(:all, :order => "title")
    (@pages.reject! {|page| !current_user.authorized_to_view?(page)}) if logged_in?
    (@pages.reject! {|page| page.private? || page.invisible?}) unless logged_in?
  end

  def show
    @page_galleries = @page.galleries.paginate :page => params[:page], :per_page => 4
  end

  def new
    @page = Page.new
  end

  def create
    @page = Page.new(params[:page])
    @page.user = current_user
    @page.save!
    flash[:update] = 'The page has been added'
    redirect_to page_url(@page)
  rescue ActiveRecord::RecordInvalid
    flash[:error] = 'There was a problem adding the page. See below.'
    redirect_to :action => 'new'
  end
  
  def edit
  end
  
  def update
    params[:page][:title_is_invisible] ||= []
    params[:page][:invisible] ||= []
    params[:page][:gallery_ids] ||= []
    params[:page][:user_ids] ||= []
    @page.user = current_user
    @page.update_attributes!(params[:page])
    flash[:update] = 'The information for this page has been updated.'
    redirect_to page_url
  rescue ActiveRecord::RecordInvalid
    flash[:error] = 'Errors were detected, see below.'
    render :action => 'edit'
  end

  def destroy
    @page.destroy
    flash[:update] = 'The page has been removed.'
    redirect_to pages_url
  end

protected
  def check_page_permissions
    if @page.private?
      if logged_in?
        unless current_user.is_admin?
          unless @page.users.include?(current_user)
            flash[:error] = "Sorry, you're not allowed to see that page."
            redirect_back_or_default('/')
          end
        end
      else
        session[:return_to] = request.request_uri
        flash[:error] = "You gotta login to see that page."
        redirect_to login_url
      end
    end
  end
  def require_login
    unless logged_in?
      flash[:error] = 'You must be logged in to see that'
      redirect_to login_url
    end
  end
  def require_admin
    if logged_in?
      unless current_user.is_admin?
        flash[:error] = "Must be an administrator to see that, sorry."
        redirect_back_or_default('/')
      end
    else
      flash[:error] = 'You must be logged in to see that'
      redirect_to login_url
    end
  end
  def find_page
    @page = Page.find(params[:id], :include => :galleries)
  end
  def find_list_items
    @galleries = Gallery.find(:all)
    @users = User.find(:all, :conditions => ['is_client = ?', true], :order => 'login desc')
  end
end
